package com.tping.linked;

/**
 * 单向环行链表
 *
 * @author zhuwj
 */
public class SinglyCircularLinked {

    private Node first;
    private Node last;
    private volatile int size;

    /**
     * 添加元素
     * @param val
     */
    public void add(int val){
        Node node = new Node(val);

        if( first == null ){
            first = node;
            first.next = first;
            last = node;
            size++;
            return;
        }

        Node cur = last;
        cur.next = node;
        node.next = first;
        last = node;
        size++;
    }

    public void outLink(int index){
        if( index <= 0 || first == null || index > size ){
            return;
        }

        Node cur = first;
        Node help = last;

        for (;;){
            if( cur == help ){
                System.out.println("最后一位出圈：" + cur.val);
                break;
            }

            // 开始报数
            for (int i = 0; i < index - 1; i++) {
                cur = cur.next;
                help = help.next;
            }

            // 出圈
            System.out.println("出圈：" + cur.val);
            cur = cur.next;
            help.next = cur;
        }
    }

    public int size(){
        return size;
    }

    public void show(){
        if( first != null ){
            Node node = first;
            for (;;){
                System.out.println("node:" + node);
                if(node.next == first) break;
                node = node.next;
            }
        }
    }

    class Node{
        private int val;
        private Node next;

        public Node(int val){
            this.val = val;
        }

        @Override
        public String toString() {
            return "Node{" + "val=" + val + '}';
        }
    }

}

